<template>
    <div id="major">
        <!-- 卡片视图区域 -->
        <el-card>
            <el-row :gutter="20">
                <el-col :span="8">
                    <!-- 搜索与添加区域 -->
                    <el-input placeholder="请输入专业名称或ID"
                        v-model="queryInfo.query"
                        clearable>
                        <template #append>
                            <el-button @click="fetchMajorList">
                                <el-icon>
                                    <search />
                                </el-icon>
                            </el-button>
                        </template>
                    </el-input>
                </el-col>
                <el-col :span="4">
                    <el-button type="primary"
                        @click="addDialogVisible = true">添加专业</el-button>
                </el-col>
            </el-row>
            <!-- 专业列表区域 -->
            <el-table :data="majorList"
                border
                stripe>
                <el-table-column type="index"></el-table-column>
                <el-table-column label="专业ID"
                    prop="majorId"></el-table-column>
                <el-table-column label="专业简称"
                    prop="majorName"
                    width="190px"></el-table-column>
                <el-table-column label="所属院系"
                    width="150">
                    <template #default="scope">
                        {{ getDepartmentName(scope.row.departmentId) || '未知院系' }}
                    </template>
                </el-table-column>
                <el-table-column label="专业全称"
                    prop="majorDescription"></el-table-column>
                <el-table-column label="操作"
                    width="200px">
                    <template v-slot="scope">
                        <!-- 修改按钮 -->
                        <el-button type="primary"
                            @click="showEditDialog(scope.row.majorId)">
                            <el-icon>
                                <edit />
                            </el-icon>
                        </el-button>
                        <!-- 删除按钮 -->
                        <el-button type="danger"
                            @click="handleDelete(scope.row.majorId)">
                            <el-icon>
                                <delete />
                            </el-icon>
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页区域 -->
            <el-pagination v-model:current-page="queryInfo.pagenum"
                v-model:page-size="queryInfo.pagesize"
                :total="total"
                :page-sizes="[10, 20, 50, 100]"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange" />
        </el-card>

        <!-- 添加专业对话框 -->
        <el-dialog v-model="addDialogVisible"
            title="添加专业"
            width="50%">
            <el-form :model="addForm"
                :rules="addFormRules"
                ref="addFormRef"
                label-width="80px">
                <el-form-item label="专业ID"
                    prop="majorId">
                    <el-input v-model="addForm.majorId"
                        autocomplete="off" />
                </el-form-item>
                <el-form-item label="专业名称"
                    prop="majorName">
                    <el-input v-model="addForm.majorName"
                        autocomplete="off" />
                </el-form-item>
                <el-form-item label="所属院系"
                    prop="departmentId">
                    <el-select v-model="addForm.departmentId"
                        placeholder="请选择所属院系"
                        :options="departmentOptions"
                        filterable
                        clearable>
                        <el-option v-for="item in departmentOptions"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="专业全称"
                    prop="majorDescription">
                    <el-input v-model="addForm.majorDescription"
                        autocomplete="off" />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="addDialogVisible = false">取消</el-button>
                <el-button type="primary"
                    @click="submitAddForm">确定</el-button>
            </template>
        </el-dialog>

        <!-- 修改专业对话框 -->
        <el-dialog v-model="editDialogVisible"
            title="修改专业信息"
            width="50%">
            <el-form :model="editForm"
                ref="editFormRef"
                label-width="80px">
                <el-form-item label="专业ID">
                    <el-input v-model="editForm.majorId"
                        disabled /> <!-- 不可修改 -->
                </el-form-item>
                <el-form-item label="专业名称"
                    prop="majorName">
                    <el-input v-model="editForm.majorName" />
                </el-form-item>
                <el-form-item label="所属院系"
                    prop="departmentId">
                    <el-select v-model="editForm.departmentId"
                        :options="departmentOptions"
                        filterable
                        clearable>
                        <el-option v-for="item in departmentOptions"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="专业全称"
                    prop="majorDescription">
                    <el-input v-model="editForm.majorDescription" />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="editDialogVisible = false">取消</el-button>
                <el-button type="primary"
                    @click="submitEditForm">保存修改</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<style scoped></style>

<script>
import { 
    getMajorList, 
    addMajor, 
    updateMajor, 
    deleteMajor,
    getMajorDetail 
} from '@/api/major';
import { getDepartmentList } from '@/api/department';

export default {
    data() {
        return {
            // 查询参数
            queryInfo: {
                pagenum: 1,       // 当前页码
                pagesize: 10,     // 每页显示数量
                query: '',        // 查询关键词
                orderBy: 0        // 排序方式(后端默认0)
            },
            // 专业列表数据
            majorList: [],
            // 院系列表数据
            departmentList: [],
            // 院系ID到名称的映射
            departmentMap: {},
            // 总数据条数
            total: 0,
            // 控制对话框显示与隐藏
            addDialogVisible: false,
            editDialogVisible: false,
            // 添加专业表单数据
            addForm: {
                majorId: "",
                majorName: "",
                departmentId: "",
                majorDescription: ""
            },
            // 添加表单验证规则
            addFormRules: {
                majorId: [{ required: true, message: "请输入专业ID", trigger: "blur" }],
                majorName: [{ required: true, message: "请输入专业名称", trigger: "blur" }],
                departmentId: [{ required: true, message: "请选择所属院系", trigger: "change" }],
                majorDescription: [{ required: true, message: "请输入专业全称", trigger: "blur" }]
            },
            // 编辑专业表单数据
            editForm: {
                majorId: "",
                majorName: "",
                departmentId: "",
                majorDescription: ""
            },
            // 编辑表单验证规则
            editFormRules: {
                majorName: [{ required: true, message: "请输入专业名称", trigger: "blur" }],
                departmentId: [{ required: true, message: "请选择所属院系", trigger: "change" }],
                majorDescription: [{ required: true, message: "请输入专业全称", trigger: "blur" }]
            },
            // 院系下拉选项
            departmentOptions: []
        };
    },
    created() {
        console.log('专业管理页面创建，开始获取数据');
        // 直接调用方法，确保方法被执行
        this.fetchMajorList();
        this.fetchDepartments();
    },
    methods: {
        // 获取专业列表
        async fetchMajorList() {
            console.log('获取专业列表，参数:', this.queryInfo);
            try {
                // 构建请求体参数
                const requestBody = {
                    majorName: this.queryInfo.query // 按专业名称搜索
                };

                // 调用API
                const res = await getMajorList(
                    this.queryInfo.pagenum,
                    this.queryInfo.pagesize,
                    this.queryInfo.orderBy,
                    requestBody
                );

                console.log('专业列表响应:', res);
                if (res.code === 200) {
                    this.majorList = res.data.list || [];
                    this.total = res.data.total || 0;
                    console.log('成功获取专业列表，共', this.total, '条数据');
                } else {
                    this.$message.error(res.message || '获取专业列表失败');
                }
            } catch (error) {
                console.error('获取专业列表失败:', error);
                this.$message.error('获取专业列表失败，请稍后再试');
            }
        },

        // 获取院系列表
        async fetchDepartments() {
            console.log('获取院系列表');
            try {
                // 调用API
                const res = await getDepartmentList(
                    this.queryInfo.pagenum,
                    this.queryInfo.pagesize,
                    this.queryInfo.orderBy,
                    {} // 空请求体
                );

                console.log('院系列表响应:', res);
                if (res.code === 200) {
                    this.departmentList = res.data.list || [];
                    // 构建院系ID到名称的映射
                    this.departmentMap = this.departmentList.reduce((map, item) => {
                        map[item.departmentId] = item.departmentName;
                        return map;
                    }, {});
                    console.log('院系映射表:', this.departmentMap);
                    
                    // 构建下拉选项
                    this.departmentOptions = this.departmentList.map(item => ({
                        value: item.departmentId,
                        label: item.departmentName
                    }));
                    console.log('院系下拉选项:', this.departmentOptions);
                } else {
                    this.$message.error(res.message || '获取院系列表失败');
                }
            } catch (error) {
                console.error('获取院系列表失败:', error);
                this.$message.error('获取院系列表失败，请稍后再试');
            }
        },

        // 根据ID获取院系名称
        getDepartmentName(departmentId) {
            // 确保ID类型一致（转为字符串）
            return this.departmentMap[String(departmentId)];
        },

        // 处理分页大小变化
        handleSizeChange(newSize) {
            this.queryInfo.pagesize = newSize;
            this.fetchMajorList();
        },

        // 处理页码变化
        handleCurrentChange(newPage) {
            this.queryInfo.pagenum = newPage;
            this.fetchMajorList();
        },

        // 显示编辑对话框
        async showEditDialog(majorId) {
            try {
                // 先获取院系列表（确保下拉框数据存在）
                await this.fetchDepartments();
                
                // 获取专业详情
                const res = await getMajorDetail(majorId);
                console.log('专业详情响应:', res);
                
                if (res.code === 200) {
                    this.editForm = res.data;
                    // 确保departmentId类型一致
                    this.editForm.departmentId = String(this.editForm.departmentId);
                    this.editDialogVisible = true;
                } else {
                    this.$message.error(res.message || '获取专业详情失败');
                }
            } catch (error) {
                console.error('获取专业详情失败:', error);
                this.$message.error('获取专业详情失败，请稍后再试');
            }
        },

        // 提交添加表单
        async submitAddForm() {
            this.$refs.addFormRef.validate(async (valid) => {
                if (valid) {
                    try {
                        // 确保departmentId类型一致
                        this.addForm.departmentId = String(this.addForm.departmentId);
                        
                        const res = await addMajor(this.addForm);
                        console.log('添加专业响应:', res);
                        
                        if (res.code === 200) {
                            this.$message.success('添加专业成功');
                            this.addDialogVisible = false;
                            // 重置表单数据
                            this.addForm = {
                                majorId: "",
                                majorName: "",
                                departmentId: "",
                                majorDescription: ""
                            };
                            // 刷新列表
                            this.fetchMajorList();
                        } else {
                            this.$message.error(res.message || '添加专业失败');
                        }
                    } catch (error) {
                        console.error('添加专业失败:', error);
                        this.$message.error('添加专业失败，请稍后再试');
                    }
                }
            });
        },

        // 提交编辑表单
        async submitEditForm() {
            this.$refs.editFormRef.validate(async (valid) => {
                if (valid) {
                    try {
                        // 确保departmentId类型一致
                        this.editForm.departmentId = String(this.editForm.departmentId);
                        
                        const res = await updateMajor(this.editForm);
                        console.log('修改专业响应:', res);
                        
                        if (res.code === 200) {
                            this.$message.success('修改专业成功');
                            this.editDialogVisible = false;
                            // 刷新列表
                            this.fetchMajorList();
                        } else {
                            this.$message.error(res.message || '修改专业失败');
                        }
                    } catch (error) {
                        console.error('修改专业失败:', error);
                        this.$message.error('修改专业失败，请稍后再试');
                    }
                }
            });
        },

        // 处理删除
        async handleDelete(majorId) {
            try {
                // 确认删除
                await this.$confirm(
                    '确认删除该专业? 此操作不可恢复', 
                    '提示', 
                    {
                        confirmButtonText: '确认',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }
                );
                
                // 调用删除API
                const res = await deleteMajor(majorId);
                console.log('删除专业响应:', res);
                
                if (res.code === 200) {
                    this.$message.success('删除专业成功');
                    // 刷新列表
                    this.fetchMajorList();
                } else {
                    this.$message.error(res.message || '删除专业失败');
                }
            } catch (error) {
                if (error !== 'cancel') {
                    console.error('删除专业失败:', error);
                    this.$message.error('删除专业失败，请稍后再试');
                }
            }
        }
    },
    // 对话框打开时刷新数据
    watch: {
        addDialogVisible(newVal) {
            if (newVal) {
                // 打开添加对话框时刷新院系列表
                this.fetchDepartments();
                // 重置表单数据
                this.addForm = {
                    majorId: "",
                    majorName: "",
                    departmentId: "",
                    majorDescription: ""
                };
            }
        },
        editDialogVisible(newVal) {
            if (newVal) {
                // 打开编辑对话框时刷新院系列表
                this.fetchDepartments();
            }
        }
    }
};
</script>